#_*_ encoding:utf-8 _*_
from menu import valid_menu

class UserMiddleware(object):
    def __init__(self, get_response=None):
        self.get_response = get_response

    def __call__(self, request):
        response = None
        if hasattr(self, 'process_request'):
            response = self.process_request(request)
        if not response:
            response = self.get_response(request)
        if hasattr(self, 'process_response'):
            response = self.process_response(request, response)
        return response

    def process_view(self,request,view_func,view_args,view_kwargs):
        pass

    def process_response(self,request,response):
        # 允许你的域名来获取我的数据
        response['Access-Control-Allow-Origin'] = "*"
        # 允许你携带Content-Type请求头
        response['Access-Control-Allow-Headers'] = "Content-Type"
        # # 允许你发送DELETE,PUT
        # response['Access-Control-Allow-Methods'] = "DELETE,PUT"
        return response

    def process_template_response(self,request,response):
        # 通过cookie设置菜单当前位置
        # last_url = request.COOKIES.get('last_url')
        # last_name = request.COOKIES.get('last_name')
        # try:
        #     urlhistory = request.COOKIES.get('urlhistory','[]')
        #     if urlhistory:
        #         urlhistory = eval(urlhistory)
        #     else:
        #         urlhistory = []
        #     if last_name:
        #         last_name = last_name.decode('utf-8')
        #         last_list = [last_url,last_name]
        #         if not last_list in urlhistory:
        #             urlhistory.append(last_list)
        #         # 当前在就截取之前的
        #         for i,uh in enumerate(urlhistory):
        #             if request.path in uh[0]:
        #                 urlhistory = urlhistory[:i]
        #                 break
        #         if len(urlhistory) > 4:
        #             urlhistory = urlhistory[1:]
        #         response.set_cookie('urlhistory',urlhistory)
        # except Exception as e:
        #     print 'urlhistory_error: %s' % e
        #     urlhistory = []
        data = {
            'MENU_LIST': valid_menu(request)
        }
        response.context_data.update(data)
        return response

    def process_exception(self,request,exception):
        pass
